//
//  CycleTool+modelWithDict.m
//  CDSBZX
//
//  Created by dihuijun on 17/3/31.
//  Copyright © 2017年 Cycle. All rights reserved.
//

#import "CycleTool+modelWithDict.h"
#import <objc/message.h>
@implementation CycleTool (modelWithDict)
/** 字典转模型*/
+ (instancetype)Cycle_modelWithDict:(NSDictionary *)dict{
    //1.得到本身,转好模型把自己返回出去,对应接收的就是数据模型
    id objc = [[self alloc]init];
    
    //count: 成员属性总数,你那边对应字典多少个成员这边就能检测到对应个数
    unsigned int count = 0;
    //2.得到所有的ivar
   Ivar *ivarList = class_copyIvarList(self, &count);
//    NSLog(@"成员总数:%zd",count);
    for (int i = 0 ; i < count ; i++) {
        ///2.1 获取成员属性
        Ivar ivar = ivarList[i];
        /// 2.1.1 获取成员名称
        NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivar)];
        /// 2.1.2 获取成员属性类型
        NSString *propertyType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        
        
        
        
        
        
        /// 2.1.3 获取key(去掉开头下划线，后面的全部要)
        NSString *key = [propertyName substringFromIndex:1];
        /// 2.1.4 获取字典中的value
        id value = dict[key];
        /*
         给模型的属性赋值
         value:字典的值
         key:属性名
         */
        
        
        ///3.1 如果这个value下面还有一个字典模型（也就是不使用NSDictionary,而是自己用的一个模型(eg:User)代替了NSDictionary）
        if ([value isKindOfClass:[NSDictionary class]] && ![propertyType containsString:@"NS"]) {
            ///值是字典，成员属性的类型不是字典，才需要转换成模型
            //得到的结果 @"@\"User\""截取出User
            NSRange range = [propertyType rangeOfString:@"\""];
            propertyType = [propertyType substringFromIndex:range.location+range.length];
            //现在是这样的 User"
            range = [propertyType rangeOfString:@"\""];
            propertyType = [propertyType substringToIndex:range.location];
            
            ///获取需要转换类的类对象
            Class modeClass = NSClassFromString(propertyType);
            if (modeClass) {
                value = [modeClass Cycle_modelWithDict:value];
            }
        }
        
        
        ///3.2 只有一层字典的时候,直接转就好了
        if(value){
            [objc setValue:value forKey:key];
        }

    }
    return objc;
}




















+ (instancetype)dict:(NSDictionary *)dic{
    
    id objc = [[self alloc]init];
    
    
    unsigned int count = 0;
    Ivar *ivarList =  class_copyIvarList(self, &count);
    for (int i =0; i<count; i++) {
        
        Ivar ivar = ivarList[i];
        
        NSString *ptName = [NSString stringWithUTF8String:ivar_getName(ivar)];
        
        NSString *ptType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        
        
        NSString *key = [ptName substringFromIndex:1];
        
        id value = dic[key];
        if(value){
             [objc setObject:value forKey:key];
        }
            
       
        
        
    }
    return objc;
    
    
    
    
    
    
    
}











@end
